package com.bzy.common.servlet;

import org.springframework.http.HttpStatus;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CorsFilter implements Filter {
	private String allowOrigin = "*";
	private String allowCredentials = "true";
	private String allowMethods = "POST,GET,PUT,DELETE,OPTIONS";
	private String maxAge = "3600";
	private String allowHeaders = "Origin,X-Requested-With,Content-Type,Accept,Cookie";

	public String getAllowOrigin() {
		return allowOrigin;
	}

	public void setAllowOrigin(String allowOrigin) {
		this.allowOrigin = allowOrigin;
	}

	public String getAllowCredentials() {
		return allowCredentials;
	}

	public void setAllowCredentials(String allowCredentials) {
		this.allowCredentials = allowCredentials;
	}

	public String getAllowMethods() {
		return allowMethods;
	}

	public void setAllowMethods(String allowMethods) {
		this.allowMethods = allowMethods;
	}

	public String getMaxAge() {
		return maxAge;
	}

	public void setMaxAge(String maxAge) {
		this.maxAge = maxAge;
	}

	public String getAllowHeaders() {
		return allowHeaders;
	}

	public void setAllowHeaders(String allowHeaders) {
		this.allowHeaders = allowHeaders;
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest reqeust, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest)reqeust;
        String origin = httpRequest.getHeader("Origin");
		httpResponse.setHeader("Access-Control-Allow-Origin", origin);
		httpResponse.setHeader("Access-Control-Allow-Credentials", allowCredentials);
		httpResponse.setHeader("Access-Control-Allow-Methods", allowMethods);
		httpResponse.setHeader("Access-Control-Max-Age", maxAge);
		httpResponse.setHeader("Access-Control-Allow-Headers", allowHeaders);
		chain.doFilter(reqeust, response);

//        String method = request.getMethod();
//        if(method.equalsIgnoreCase("OPTIONS")){
//            servletResponse.getOutputStream().write("Success".getBytes("utf-8"));
//        }else{
//            filterChain.doFilter(servletRequest, servletResponse);
//        }
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
